'use strict';

import {makeList} from "@shenfengshan-cli/inquirer"

import log from "@shenfengshan-cli/log"

import Ali from "./src/ali.js";
import Github from "./src/github.js";
import Gitee from "./src/gitee.js";
import {getGitPlatform, clearCache, getGitOwn, getGitLogin} from "./server.js";


export const initServer = async () => {
    let platform = getGitPlatform()

    if (!platform) {
        platform = await makeList({
            message: "请选择平台",
            choices: [
                {name: "github", value: "github"},
                {name: "gitee", value: "gitee"},
                {name: "ali", value: "ali"},
            ]
        })
    }
    log.verbose("platform", platform)
    let gitServer = null
    switch (platform) {
        case "github":
            gitServer = new Github()
            break
        case "gitee" :
            gitServer = new Gitee()
            break
    }
    gitServer.savePlatform(platform)
    await gitServer.init()
    return gitServer
}


export async function initGitType(serve) {
    let gitOwn = getGitOwn(); // 仓库类型
    let gitLogin = getGitLogin(); // 仓库登录名
    if (!gitLogin && !gitOwn) {
        const user = await serve.getUser();
        const org = await serve.getOrg();
        log.verbose('user', user);
        log.verbose('org', org);
        if (!gitOwn) {
            gitOwn = await makeList({
                message: '请选择仓库类型',
                choices: [{
                    name: 'User', value: 'user',
                }, {
                    name: 'Organization', value: 'org',
                }],
            });
            log.verbose('gitOwn', gitOwn);
        }
        if (gitOwn === 'user') {
            gitLogin = user?.login;
        } else {
            const orgList = org.map(item => ({
                name: item.name || item.login,
                value: item.login,
            }));
            gitLogin = await makeList({
                message: '请选择组织',
                choices: orgList,
            });
        }
        log.verbose('gitLogin', gitLogin);

    }
    if (!gitLogin || !gitOwn) {
        throw new Error('未获取到用户的Git登录信息！请使用"sfs-cli commit --clear"清除缓存后重试');
    }
    serve.saveOwn(gitOwn);
    serve.saveLogin(gitLogin);
    return gitLogin;
}

export async function createRemoteRepo(gitAPI, name) {
    const ret = await gitAPI.createRepo(name);
}


export {
    Ali, Gitee, Github, getGitPlatform, clearCache
}
